<!--
 * @Description:用户管理页面
-->
<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
        (searchlist = { ...e }), (currentPage = 1), getTableDataList();
      }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData @selection-change="selectionChange" :config="table_config" :tableThead="tableThead"
        :dataList="dataList">
        <template v-slot:roleNames="{ row }">
          <span v-for="(item, index) in row.roleNames" :key="index">
            {{ item }}
            <span v-show="index < row.roleNames.length - 1">、</span>
          </span>
        </template>
        <template v-slot:personNo="{ row }">
          <el-switch v-model="row.expire" :active-value="'启用'" :inactive-value="'禁用'" @change="faciStatus(row)" />
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <!-- 添加和修改密码公用 -->
      <el-dialog :close-on-click-modal="false" :title="titleText + '用户信息'" :visible.sync="dialogFormVisible"
        :before-close="cancel" width="40%">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="80px" class="demo-ruleForm">
          <el-form-item v-show="formData.personif !== 'lessee' && nowChanceStau == 'add'" label="员工" prop="personNo"
            class="w100p">
            <el-select v-model="formData.personNo" filterable clearable @change="staffPerson" class="w100p">
              <el-option v-for="(item, index) in staffData" :key="index" :label="item.person.name"
                :value="item.personNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname" class="w100p">
            <el-input v-model="formData.nickname" clearable placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="账号" prop="username" class="w100p">
            <el-input v-model="formData.username" :disabled="nowChanceStau == 'edit'" clearable placeholder="请输入账号" />
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'editPassword'" :label="'旧密码:'" prop="oldPassword" class="w100p">
            <el-input v-model="formData.oldPassword" show-password type="password" clearable autocomplete="off" />
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'editPassword' && formData.oldPassword" label="新密码" prop="newPassword"
            class="w100p">
            <el-input v-model="formData.newPassword" show-password type="password" clearable />
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'editPassword' && formData.oldPassword" label="确认密码" prop="newPasswords"
            class="w100p">
            <el-input v-model="formData.newPasswords" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item v-if="!formData.personNo && nowChanceStau === 'add'" label="姓名" prop="name" class="w100p">
            <el-input v-model="formData.name" placeholder="请输入员工姓名" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="性别" prop="gender" class="w100p">
            <el-select class="w100p" v-model="formData.gender" filterable clearable>
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="身份证号" prop="identificationNumber" class="w100p">
            <el-input v-model="formData.identificationNumber" placeholder="身份证号" />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="手机号" prop="phone" class="w100p">
            <el-input v-model="formData.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="座机号" prop="landline" class="w100p">
            <el-input v-model="formData.landline" placeholder="请输入座机号" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="邮箱" prop="email" class="w100p">
            <el-input v-model="formData.email" type="email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="微信" prop="weChat" class="w100p">
            <el-input v-model="formData.weChat" placeholder="请输入微信" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="住址" prop="address" class="w100p">
            <el-input v-model="formData.address" placeholder="请输入住址" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.personNo" label="生日" prop="birthday" class="w100p">
            <el-date-picker v-model="formData.birthday" type="date" value-format="yyyy-MM-dd" placeholder="请选择生日日期"
              clearable filterable class="w100p" />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <!-- TODO:修改信息 -->
      <el-dialog :close-on-click-modal="false" :title="titleText + '用户信息'" :visible.sync="dialogFormVisibles"
        @close="cancel('formData1')" width="40%">
        <el-form ref="formData1" :model="formData" :rules="rules" label-width="80px" class="demo-ruleForm">
          <el-form-item v-if="formData.personif !== 'lessee'" label="员工" prop="personNo">
            <el-select v-model="formData.personNo" filterable clearable @change="staffPerson" class="w100p">
              <el-option v-for="(item, index) in staffData" :key="index" :label="item.person.name"
                :value="item.personNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" filterable clearable class="w100p">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="身份证号" prop="identificationNumber" class="w100p">
            <el-input v-model="formData.identificationNumber" placeholder="身份证号" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone" class="w100p">
            <el-input v-model="formData.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item label="座机号" prop="landline" class="w100p">
            <el-input v-model="formData.landline" placeholder="请输入座机号" clearable />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" class="w100p">
            <el-input v-model="formData.email" type="email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          <el-form-item label="微信" prop="weChat" class="w100p">
            <el-input v-model="formData.weChat" placeholder="请输入微信" clearable />
          </el-form-item>
          <el-form-item label="住址" prop="address" class="w100p">
            <el-input v-model="formData.address" placeholder="请输入住址" clearable />
          </el-form-item>
          <el-form-item label="生日" prop="birthday" class="w100p">
            <el-date-picker class="w100p" v-model="formData.birthday" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择生日日期" clearable filterable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="editsadd('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="分配角色" :visible.sync="dialogFormAssignVisible"
        :before-close="closeDialog" width="40%">
        <assignroleComponent v-if="dialogFormAssignVisible" ref="assignrole" :username="formData.username"
          :userstu="userstu" @users="users" />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogFormAssignVisible = false">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="userAdd('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="功能权限" :visible.sync="dialogFormFuthDataVisible"
        :before-close="cancelAssign" width="40%">
        <DataAuthComponent v-if="dialogFormFuthDataVisible" ref="assignrole" :username="formData.username"
          :userstu="userstu" @users="users" />
        <div slot="footer" class="dialog-footer">
          <!-- <el-button
            class="zh-button-one"
            @click="dialogFormFuthDataVisible = false"
          >
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="userAdd">
            保 存
          </el-button>-->
          <el-button class="zh-button-two" type="primary" @click="saveRole('formData')">关 闭</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="分配App功能权限" :visible.sync="dialogDataAppAuthFormVisible"
        width="40%">
        <DataAppAuthComponent v-if="dialogDataAppAuthFormVisible" ref="funcAuth" :username="formData.username"
          :userstu="userstu" @users="users" />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="userAdd('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="用户审核" :visible.sync="dialogExamineFormVisible" class="Examine"
        width="40%">
        <el-table v-loading="loading" :data="auditTableData" stripe border>
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="username" label="账号" />
          <el-table-column prop="person.name" label="姓名" />
          <el-table-column prop="person.phone" label="手机号" />
          <el-table-column width="200" label="操作">
            <template v-if="scope.row.personNo" slot-scope="scope">
              <el-button class="text-btn-cursor" type="text" size="small" @click="AuditStatus(scope.row, 1)">
                <i class="el-icon-tickets"></i> 通过
              </el-button>
              <el-button class="text-btn-cursor cursor-delete" type="text" size="small"
                @click="AuditStatus(scope.row, 2)">
                <i class="el-icon-close"></i> 不通过
              </el-button>
              <!-- <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="问题" :visible.sync="showEncrypted" width="40%">
        <div v-if="encryptedQuestionList.length === 0" style="font-size: 20px">
          你还没有密保，请点击右下角添加密保
        </div>
        <div v-else style="height: 100%">
          <el-table :data="encryptedQuestionList" style="width: 100%">
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="question" label="问题" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button class="text-btn-cursor" type="text" size="small" @click="editEncrypted(scope.row)">
                  <i class="el-icon-tickets"></i>修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="encryptedQuestionList.length === 0" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showEncrypted = false">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="addEncrypted()">添 加</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="修改密保" :visible.sync="showEditEncrypted" width="20%">
        <el-form ref="encrypted" :model="encrypted" :rules="encryptedRules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="问题：" prop="question">
            <el-input v-model="encrypted.question" class="w100p" />
          </el-form-item>
          <el-form-item label="密保：" prop="password">
            <el-input v-model="encrypted.password" type="password" class="w100p" />
          </el-form-item>
          <el-form-item label="确认密保：" prop="confirmPassword">
            <el-input v-model="encrypted.confirmPassword" type="password" class="w100p" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showEditEncrypted = false">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="editSaveEncrypted('encrypted')">修 改</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="添加密保" :visible.sync="showAddEncrypted" width="40%">
        <el-form ref="formData1" :model="formData1" :rules="addEncryptedrules" label-width="100px"
          class="demo-ruleForm">
          <div v-for="(item, index) in formData1.securityQuestionList" :key="index">
            <el-form-item :label="'密保问题' + (index + 1)" :prop="'securityQuestionList.' + index + '.question'" :rules="[
              {
                required: true,
                message: '问题不能为空',
                trigger: 'blur',
              },
              {
                min: 5,
                max: 100,
                message: '长度在 5 到 100 个字符',
                trigger: 'blur',
              },
            ]">
              <el-input v-model="item.question" class="w100p" />
            </el-form-item>
            <el-form-item :label="'密保答案' + (index + 1)" :prop="'securityQuestionList.' + index + '.securityAnswer'"
              :rules="[
                {
                  required: true,
                  message: '答案不能为空',
                  trigger: 'blur',
                },
                {
                  min: 1,
                  max: 100,
                  message: '长度在 1 到 100 个字符',
                  trigger: 'blur',
                },
              ]">
              <el-input v-model="item.securityAnswer" class="w100p" />
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="(showAddEncrypted = false), (showEncrypted = false)">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="AddSaveEncrypted('formData1')">添 加</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import userManage from "@/api/system-settings/user-manage";
import personManage from "@/api/livestock-manage/personnel-cost-mansge/staff-manage/index.js";
import tenantManage from "@/api/livestock-manage/tenant-manage/tenant-info/index.js";

import assignroleComponent from "../components/assign-rolle-component";
import DataAuthComponent from "../components/func-auth-user-component";
import DataAppAuthComponent from "../components/App-user-component";
import axios from "axios";
import $baseUrl from "@/utils/baseURL";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
export default {
  name: "UserManage",
  components: {
    MainSlot,
    SearchForm,
    BtnSlot,
    Pagination,
    TableData,

    DataAuthComponent,
    assignroleComponent,
    DataAppAuthComponent,
  },
  mixins: [mymixin],
  data() {
    var checkIdentitytionId = (rule, value, callback) => {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (value === "" || value === undefined || value === null) {
        callback();
      } else {
        if (!reg.test(value) && value !== "") {
          callback(new Error("请输入正确的身份证号码"));
        } else {
          callback();
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.formData.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密保"));
      } else if (value !== this.encrypted.password) {
        callback(new Error("两次输入密保不一致!"));
      } else {
        callback();
      }
    };
    return {
      nowChanceStau: '',
      formItemList: [
        {
          label: "用户昵称",
          type: "input",
          param: "nickname",
          isShow: true,
        },
      ], //搜索
      searchlist: {},
      selectionList: [],
      tableThead: [
        { isShow: true, label: "昵称", prop: "nickname" },
        { isShow: true, label: "账号", prop: "username" },
        { isShow: true, label: "角色", slotName: "roleNames" },
        { isShow: true, label: "状态", slotName: "personNo" },
      ],
      btnList: ["add"],
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      dataList: [],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "500",
          cols: [
            {
              label: "修改密保",
              type: "primary",
              flag: "editConfident",
              handleRow: this.handleRow,
            },
            {
              label: "分配角色",
              type: "success",
              flag: "assignRole",
              handleRow: this.handleRow,
            },
            {
              label: "重置密码",
              type: "info",
              flag: "resetPassword",
              handleRow: this.handleRow,
            },
            {
              label: "修改信息",
              type: "info",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "修改密码",
              type: "info",
              flag: "editPassword",
              handleRow: this.handleRow,
            },
          ],
        },
      },
      //   ===========================cv
      // 密保相关
      formData1: {
        securityQuestionList: [
          { question: "", securityAnswer: "" },
          { question: "", securityAnswer: "" },
          { question: "", securityAnswer: "" },
        ],
      },
      encrypted: {
        question: "",
        password: "",
        confirmPassword: "",
        securityQuestionNo: "",
      },
      encryptedQuestionList: [],
      // encryptedQuestion: '',
      account: "",
      showEncrypted: false,
      showAddEncrypted: false,
      showEditEncrypted: false,
      // 右侧权限展示1主界面,2功能权限,3数据权限,4分配角色
      nowpage: 1,
      // 操作按钮的逻辑及展示数据
      addActive: true,
      editActive: false,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      funcAuthActive: false,
      // 数据权限
      dataAuthActive: false,
      // 分配角色
      assignRoleActive: false,
      funcAppAuthActive: false,
      dialogDataAppAuthFormVisible: false,
      dialogExamineFormVisible: false,
      // table
      loading: true,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      total: 0,
      // 员工姓名
      username: "",
      // 是否能输入
      canInput: false,
      tableData: [],
      formData: {},
      lesseeData: [],
      rules: {
        username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        oldPassword: [
          { required: true, message: "请输旧密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        newPasswords: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: validatePass2,
            trigger: "blur",
          },
        ],
        gender: [
          {
            required: true,
            message: "请选择性别",
            trigger: ["change", "blur"],
          },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        identificationNumber: [
          { required: true, message: "请输入身份证", trigger: "blur" },
          { validator: checkIdentitytionId, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          {
            required: true,
            message: "请输入手机号",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^1[3-9]\d{9}$/, // 手机号正则表达式，这里假设只验证中国大陆手机号
            message: "手机号格式不正确",
            trigger: ["blur", "change"],
          },
        ],
        email: [
          { message: "请输入邮箱", trigger: "blur" },
          //   {
          //     validator: function (rule, value, callback) {
          //       if (
          //         /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
          //           value
          //         ) == false
          //       ) {
          //         callback(new Error("邮箱格式错误"));
          //       } else {
          //         callback();
          //       }
          //     },
          //     trigger: ["change", "blur"],
          //   },
        ],
        weChat: [
          {
            message: "请输入微信号",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/,
            message: "请输入正确的微信号",
          },
        ],
      },
      encryptedRules: {
        question: [{ required: true, message: "请输入问题", trigger: "blur" }],
        password: [{ required: true, message: "请输入密保", trigger: "blur" }],
        confirmPassword: [
          { required: true, message: "请再次输入密保", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      },
      addEncryptedrules: {},
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      dialogFormVisibles: false,
      dialogFormAssignVisible: false,
      dialogFormFuthDataVisible: false,
      staffData: [],
      userstu: "",
      auditusername: "",
      auditTableData: [],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    // 获取表格数据
    this.account = sessionStorage.account;
    this.getTableDataList();
    this.selectData();
  },
  mounted() { },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "funcAuthShow") {
        if (this.selectionList.length == 1) {
          this.funcAppAuthShow();
        } else {
          this.$message.warning("请选择单个数据项");
        }
      }
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    // 操作方法
    handleRow(rowData, item) {
      console.log(rowData, item, "rowData, item,rowData, item");
      if (item.flag == "editConfident") {
        this.account = rowData.account
        this.assignEncrypted(rowData.account);
      } else if (item.flag == "assignRole") {
        this.assignRoleShow(rowData);
      } else if (item.flag == "resetPassword") {
        this.reset(rowData);
      } else if (item.flag == "edit") {
        this.edits(rowData);
      } else if (item.flag == "editPassword") {
        this.editPassword({
          ...rowData,
          newPasswords: '',
          newPassword: '',
          oldPassword: ''
        });
      }
    },
    // TODO:重置密码
    async reset(row) {
      this.$confirm("你确定要对此用户重置密码吗？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(async () => {
          let params = { username: row.username };
          let res = await userManage.resetPassword(params);
          if (res.code == 1) {
            let ress = await userManage.getResetPassword();
            this.$message.success(`密码重置成功！初始密码为${ress}`);
          } else {
            this.$message.warning("密码重置失败！");
          }
        })
        .catch((action) => {
          //   this.$message({
          //     type: "info",
          //     message: "你已取消重置密码！",
          //   });
        });
    },
    saveRole() {
      this.dialogFormFuthDataVisible = false;
      this.funcAuthActive = false;
      // this.rolestu = 'add'
    },
    userAdd() {
      //   console.log(this.formData)
      this.userstu = "add";
    },
    users() {
      this.userstu = "";
      this.dialogFormAssignVisible = false;
      this.dialogExamineFormVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.showEncrypted = false;
      this.showEditEncrypted = false;
      this.showAddEncrypted = false;
      this.getTableDataList();
    },
    // 获取下拉框数据
    async selectData() {
      const { data: resStaff } = await personManage.getStaffListByCondition();
      this.staffData = resStaff;
    },
    staffPerson(e) {
      if (!e) {
        this.$set(this.formData, "personNo", undefined);
        this.$set(this.formData, "personif", "");
      } else {
        this.$set(this.formData, "personif", "staff");
      }
    },
    lesseePerson(e) {
      if (!e) {
        this.$set(this.formData, "personNo", undefined);
        this.$set(this.formData, "personif", "");
      } else {
        this.$set(this.formData, "personif", "lessee");
      }
    },
    funcExamineAuthShow() {
      this.dialogExamineFormVisible = true;
      this.auditUsercs();
    },
    // 审核分页查询
    async auditUsercs() {
      let params = {
        page: 1,
        size: 1000,
        entity: {
          username: this.auditusername || undefined,
          auditFlag: 0,
          organizationNo: sessionStorage.organizationNo,
        },
      };
      const { data: res } = await personManage.auditUserByConditio(params);
      this.auditTableData = res.content;
    },
    async AuditStatus(e, st) {
      let params = {
        ...e,
      };
      params.auditFlag = st;
      const res = await personManage.auditUserStatus(params);
      if (res.code === 1) {
        this.auditUsercs();
        if (st === 1) {
          this.formData.username = res.data.username;
          this.dialogFormAssignVisible = true;
        }
      } else {
        this.$message.warning("审核失败");
      }
    },
    getTableDataList() {
      this.loading = true;
      console.log(this.searchlist);
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          organizationNo: sessionStorage.organizationNo,
          nickname: this.searchlist.nickname,
        },
        // notAdmin: true
      };
      // console.log(params)
      userManage.getUserStaffList(params).then((res) => {
        this.loading = false;
        let data = res.data;
        // console.log(data);
        // 赋值总条数
        this.total = data.totalElements;
        // 赋值数组
        this.dataList = data.content;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize;
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({ indflag: i + this.tableData.length - 1 });
          }
        }
      }
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = "";
      this.addActive = true;
      this.editActive = false;
      this.delActive = false;
      this.saveActive = false;
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignRoleActive = false;
      this.cancelActive = false;
      this.canInput = false;
      this.formData = {};
      this.dialogFormAssignVisible = false;
      this.funcAppAuthActive = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.showEncrypted = false;
      this.showEditEncrypted = false;
      this.showAddEncrypted = false;
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      this.formData = JSON.parse(JSON.stringify(row));
      if (row.personNo) {
        this.editActive = true;
        this.funcAuthActive = true;
        this.assignRoleActive = true;
        this.cancelActive = true;
      } else {
        this.resetActionBar();
      }
      // this.openDialog("edit");
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.employeeId);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;

      // 多个处理为单个数据
      if (this.selectedStaffList.length > 1) {
        this.$message.warning("员工不可多选删除！");
        this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
        console.log(this.selectedStaffList);
      }
    },
    faciStatus(e) {
      this.$confirm("是否禁用", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            ...e,
          };
          // console.log(e)
          // if (e.expire === '启用') {
          //   params.expire = '禁用'
          // } else if (e.expire === '禁用') {
          //   this.$set(params, "expire", '启用')
          // }
          // // this.formData.topOrganization = sessionStorage.topOrganization;
          // // this.formData.organizationNo = [sessionStorage.organizationNo];
          // console.log(params)
          userManage.editUserInfo(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("修改成功！");
              this.closeDialog();
              this.resetActionBar();
              this.getTableDataList();
            }
          });
          this.$nextTick(() => {
            setTimeout(() => {
              this.getTableDataList();
            }, 300);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.getTableDataList();
          // this.resetActionBar();
        });
    },
    // 点击功能权限触发的方法
    funcAuthShow() {
      this.nowpage = 1;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      // console.log("点击了功能权限");
      this.dialogFormFuthDataVisible = true;
      this.saveActive = true;
    },
    // 点击数据权限触发的方法
    dataAuthShow() {
      this.nowpage = 1;
      this.cancelActive = true;
      this.addActive = false;
      this.editActive = false;
      console.log("点击了数据权限");
      this.saveActive = true;
    },
    // 显示密保框
    assignEncrypted(account) {
      this.showEncrypted = true;
      // 获取密保问题
      userManage.getEncryptedquestion(account).then((res) => {
        if (res.code === 1) {
          this.encryptedQuestionList = res.data || [];
        }
      });
    },
    // 修改密保
    editEncrypted(row) {
      this.encrypted = {};
      console.log(row);
      this.showEditEncrypted = true;
      this.encrypted = { ...row };
    },
    editSaveEncrypted(encrypted) {
      this.$refs[encrypted].validate((valid) => {
        if (valid) {
          // alert('submit!');
          let params = {
            question: this.encrypted.question,
            newAnswer: this.encrypted.password,
            securityQuestionNo: this.encrypted.securityQuestionNo,
          };
          userManage.editEncrypted(params).then((res) => {
            console.log(res);
            if (res.code === 1) {
              this.showEditEncrypted = false;
              this.encrypted = {};
              this.$message.success(res.msg);
              this.assignEncrypted();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加密保问题
    addEncrypted() {
      this.showAddEncrypted = true;
      this.formData1 = {
        securityQuestionList: [
          { question: "", securityAnswer: "" },
          { question: "", securityAnswer: "" },
          { question: "", securityAnswer: "" },
        ],
      };
    },
    AddSaveEncrypted(formData1) {
      this.$refs[formData1].validate((valid) => {
        if (valid) {
          this.formData1.securityQuestionList.map((item) => {
            item.userName = this.account;
          });
          userManage.addManyEncrypted(this.formData1).then((res) => {
            console.log(res);
            if (res.code === 1) {
              this.$message.success(res.msg);
              // this.assignEncrypted()
              this.showAddEncrypted = false;
              this.formData1 = {
                securityQuestionList: [
                  { question: "", securityAnswer: "" },
                  { question: "", securityAnswer: "" },
                  { question: "", securityAnswer: "" },
                ],
              };
              this.showEncrypted = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 点击了分配角色
    assignRoleShow(data) {
      // this.nowpage = 4;
      this.dialogFormAssignVisible = true;
      this.formData = data;
    },
    funcAppAuthShow() {
      this.dialogDataAppAuthFormVisible = true;
    },
    async edits(e) {
      this.nowChanceStau = "edit";
      this.titleText = "修改";
      const { data: res } = await userManage.Syst(e.personNo);
      this.formData = {
        ...e,
        ...res,
      };
      console.log(this.formData, "===========================修改");
      this.canInput = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
      this.dialogFormVisibles = true;
      this.showAddEncrypted = false;
    },
    // 修改
    editsadd() {
      this.$refs.formData1.validate((valid) => {
        if (valid) {
          let params = {
            ...this.formData,
            person: {
              ...this.formData,
            },
          };
          userManage.editpersonInfo(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("修改成功！");
              this.closeDialog();
              this.resetActionBar();
              this.getTableDataList();
            }
          });
        } else {
          return false;
        }
      });
    },

    cancel(formdata1) {
      this.formData = {};
      if (formdata1 === "formData1") {
        this.$nextTick(() => {
          this.$refs.formData1.resetFields();
        });
      } else {
        this.$nextTick(() => {
          // this.$refs.formData.resetFields();
          this.$refs.formData.clearValidate();
          this.formData = {};
        });
      }
      this.showEditEncrypted = false;
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignUserActive = false;
      this.funcAppAuthActive = false;
      this.assignRoleActive = false;
      this.cancelActive = false;
      this.dialogFormVisibles = false;
      this.dialogFormVisible = false;
      this.addActive = true;
      this.dialogDataAppAuthFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.showEncrypted = false;
      this.showAddEncrypted = false;
    },
    del() {
      this.$message.warning("用户不允许删除");
      // userManage
      //   .delInspectionRouteInfo(this.inspectionRouteIdList)
      //   .then(res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       this.getTableDataList();
      //     }
      //   });
    },
    cancelAssign() {
      this.closeDialog();
    },
    // 添加
    save(formData) {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          if (this.nowChanceStau === "editPassword" && this.nowpage === 1) {
            // this.formData.organizationNo = [sessionStorage.organizationNo];
            // this.formData.topOrganization = sessionStorage.topOrganization;
            // console.log(this.formData.oldPassword)
            if (
              this.formData.oldPassword !== undefined &&
              this.formData.oldPassword !== ""
            ) {
              await this.editPass();
            }
          } else if (this.nowChanceStau === "add" && this.nowpage === 1) {
            // 新增接口
            if (!this.formData.personNo) {
              let from = JSON.parse(JSON.stringify(this.formData));
              // this.$set(this.formData)
              this.formData = {
                person: {
                  ...from,
                },
                nickname: from.nickname,
                username: from.username,
                account: from.username,
                // TODO:测试阶段--最终不要密码
                password: from.password,
              };
            }
            this.formData.organizationNo = [sessionStorage.organizationNo];
            this.formData.topOrganization = sessionStorage.topOrganization;
            this.formData.account = this.formData.username;
            this.formData.expire = "启用";
            // return
            this.registerIofo(this.formData);
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },

    // 修改密码
    editPass() {
      let zhurl =
        $baseUrl.agricultureServiceUrl +
        "v3/virtualSystem/v1/user/resetPassword";
      let data = `username=${this.formData.username}&oldPassword=${this.formData.oldPassword}&newPassword=${this.formData.newPassword}`;
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: sessionStorage.getItem("databaseName"),
          accessToken:
            store.getters.token ||
            sessionStorage.getItem("token") ||
            getToken(),
          organizationList: sessionStorage.getItem("organizationNoList"),
          organizationNo: sessionStorage.getItem("organizationNo"),
          virtualSystemNo: sessionStorage.getItem("Virtualsystemno"),
        },
        data: data,
      }).then((res) => {
        if (res.data.code === 1) {
          this.getTableDataList();
          this.closeDialog();
          this.resetActionBar();
          this.$message.success("密码修改成功");
        } else {
          this.$message.warning(res.data.msg || '密码修改失败');
        }
      });
    },
    registerIofo(params, sysDataBaseName) {
      let zhurl =
        $baseUrl.agricultureServiceUrl + "v3/virtualSystem/v1/user/add";
      axios({
        method: "POST",
        url: zhurl,
        headers: {
          databaseName: sessionStorage.getItem("databaseName"),
          accessToken:
            store.getters.token ||
            sessionStorage.getItem("token") ||
            getToken(),
          organizationList: sessionStorage.getItem("organizationNoList"),
          organizationNo: sessionStorage.getItem("organizationNo"),
          virtualSystemNo: sessionStorage.getItem("Virtualsystemno"),
        },
        data: {
          ...params,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.closeDialog();
          this.getTableDataList();
          this.$message.success("添加成功!用户初始密码为：123456");
        } else {
          this.$message.warning(`${res.data.msg}`);
        }
      });
    },
    editPassword(row) {
      this.openDialog("editPassword");
      this.formData = row;
      this.titleText = "修改";
      this.nowChanceStau = 'editPassword';
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.showAddEncrypted = false;
      this.showEditEncrypted = false;
      this.showEncrypted = false;
      this.dialogFormVisible = false;
      this.dialogFormVisibles = false;
      this.dialogFormAssignVisible = false;
      this.dialogFormFuthDataVisible = false;
      this.dialogDataAppAuthFormVisible = false;
      this.dialogTitle = null;
      this.addActive = true;
      this.nowChanceStau = "";
    },
  },
};
</script>

<style scoped lang="scss"></style>
